<template>
<gj-loadmore :bottom-method="loadBottom" :bottomPullText="bottomPullText" ref="loadmore">
<div class="rockstock-list stock-list">
<div class="hbox">
    <div class='none-data' v-if="dataList.length==0">{{noDataDescribe}}</div>
    <div v-else class="hbox-row" v-for="(item,index) in dataList" @click="clickRow(item)">
        <div class="col-1 hbox-row-item">
            <div class="rank" v-if="index>2">{{index+1}}</div>
        </div>
        <div class="col-2 hbox-row-item">
            <div class="stock_name">{{item.stock_name}}</div>
            <div class="stock_code">{{item.stock_code || "--"}}</div>
        </div>
        <div class="col-3 hbox-row-item">
            <div class="last_price">{{priceFormat(item.last_price)}}</div>
            <span>当前价</span>
        </div>
        <div class="col-4 hbox-row-item">
            <div class="buyer_num">{{item.vol}}</div>
            <span>{{NumberDescription}}</span>
        </div>
        <div class="col-5 hbox-row-item" @click.stop="addRemoveStock(item)">
            <div class="self-btn" :class="{'gray':item.actionState==1,'add':item.actionState==2,'remove':item.actionState==3}">
                <i class="iconfont" v-if="item.actionState==3">&#xe600;</i>
                <i class="iconfont" v-else>&#xe602;</i>
                <div>{{buttonText(item)}}</div>
            </div>
        </div>
    </div>
</div>
</div>
</gj-loadmore>
</template>

<script>
import RemoteDAO from 'common/remoteDAO'
import LocalDAO from 'common/localDAO'
import CommonUtil from 'common/common.util'
import LoadMore from 'components/LoadMore'

export default {
    components:{
        "gj-loadmore":LoadMore
    },
	data(){
		return {
			// tabIndex:0,
			userCode:null,
			dataList:[],
			stockcodes:'',
            myStocks:[],
            islogin:false,
			noDataDescribe:"暂无数据",
			pageInfo:{
				pageNum:0,
                pageSize:10
			},
            bottomPullText:"上拉加载更多牛股"
		}
	},
    watch: {
        '$route.params.menuindex':{
            handler: function (to, from) {
              this.dataList = [];
              this.stockcodes = "";
              this.pageInfo.pageNum = 0;
              this.$refs.loadmore.reset();

              this.sendStockEvent(to);
            },
            deep: true
        }
    },
	computed:{
		NumberDescription(){
			var vm = this;

            switch(Number(vm.$route.params.menuindex)){
                case 0:
                    return "模拟买入人数";
                case 1:
                    return "模拟卖出人数";
                case 2:
                    return "添加自选人数";
            }
		}
	},
	methods:{
        priceFormat(value){
            return CommonUtil.toFixed(value,2);
        },
        getPageParam(){
            return {
                start:this.pageInfo.pageNum*this.pageInfo.pageSize,
                end:(this.pageInfo.pageNum+1)*this.pageInfo.pageSize
            }
        },
        loadBottom() {
            let vm = this;

            vm.fetchData(function (allLoaded,error) {
              if(error){
                vm.$refs.loadmore.onBottomError(error);//单次加载失败或者没有数据，error为报错信息，如果是没有数据，写暂无数据
              }else if (allLoaded) {
                vm.$refs.loadmore.onBottomAllLoaded();//全部数据加载完成
              } else {
                vm.$refs.loadmore.onBottomLoaded(); //单次加载成功
              }
            });
        },
        clickRow(item){
        	//点击行跳转
        	var vm = this;

        	RemoteDAO.callStockLive(item.stock_code, "ordinary", vm.islogin, function (data) {
        	});
        },
		//不能操作、加自选、删自选
		actionState(item){
			if(item.stock_code == "-"){
				return 1;
			} else if(Number(item.optionstock_flag) != 1){
				return 2;
			} else {
				return 3;
			}
		},
		//加自选、删自选按钮文字说明
		buttonText(item){
			var vm = this;

			switch (item.actionState) {
				case 1:
				case 2:
					return "加自选";
				case 3:
					return "删自选";
			}
		},
		//更新实时行情
		updateLive(start,end){
            var vm = this;
			//调取原生实时行情接口
            var stockcodes = vm.stockcodes.substring(0, vm.stockcodes.length - 1); //去掉最后的"|"
            RemoteDAO.callNativeLiveStockPrice(vm.stockcodes, function (ret) {
                if (ret.error == 0) {
                    for(var i=0;i<vm.dataList.length;i++){
                        vm.dataList[i].last_price = ret.data[i].price;
                    }
                }
                if (vm.$route.params.menuindex == "0") {
                    LocalDAO.setRockStockBuy({"stockList": JSON.parse(JSON.stringify(vm.dataList))});
                } else if(vm.$route.params.menuindex == "1")  {
                    LocalDAO.setRockStockSell({"stockList": JSON.parse(JSON.stringify(vm.dataList))});
                }
            });
		},
		checkMyStock(start,end){
            var vm = this;

            if(vm.myStocks.length==0){
                //自选股查询
                RemoteDAO.callSelfList(function (res) {
                    if (res.error == 0) {
                        vm.myStocks = res.data;
                    } else {
                        vm.myStocks = [];
                    }

                    _isMyStock();//遍历是否是自选股
                    vm.updateLive(start,end);
                });
            } else {
                _isMyStock();//遍历是否是自选股
                vm.updateLive(start,end);
            }

            function _isMyStock() {
                for(var i=start;i<end;i++){
                    if (_.indexOf(vm.myStocks, vm.dataList[i].stock_code) > -1) {
                        vm.dataList[i].optionstock_flag = "1";
                    } else {
                        vm.dataList[i].optionstock_flag = "0";
                    }
                    vm.dataList[i].actionState = vm.actionState(vm.dataList[i]);
                }
            };
		},
		//获取牛人都在看数据
		fetchWatchData(afterFetchData){
			//查询牛人都在看
			var vm = this,
                error = '',
                allLoaded = false,
                start = vm.pageInfo.pageSize*vm.pageInfo.pageNum,
                end;

            vm.userCode = LocalDAO.getUserCode() || "49008";
            RemoteDAO.callUC12008305(vm.user_code, vm.pageInfo.pageSize, vm.pageInfo.pageNum, function (response) {
                if (Number(response.error) == 0) {
                    var models = [];

                    response.data.body.forEach(function (stock, index) { //让用户中心查询出来的字段改成金策略的字段
                        var obj = {
                            "stock_name": stock.STOCK_NAME,
                            "stock_code": CommonUtil.getMarketCode(stock.MARKET) + stock.STOCK_CODE,
                            "exchange_type": stock.MARKET,
                            "vol": stock.OPTIONSTOCK_COUNT || "-",
                            "optionstock_flag": stock.OPTIONSTOCK_FLAG,
                            "last_price": 0
                        };
                        vm.stockcodes += obj.stock_code + "|";  //拼接的股票字符串，供调用原生行情接口使用。
                        obj.actionState = "1";
                        models.push(obj);
                    });

                    vm.dataList = vm.dataList.concat(models);

                    if(vm.dataList.length == 0){
                      error = '暂无数据'
                    }else if (response.data.body.length < vm.pageInfo.pageSize){
                      allLoaded = true
                    }

                    if(!allLoaded){
                        vm.pageInfo.pageNum++;
                    }

                    end = start+response.data.body.length;
                    vm.checkMyStock(start,end);
                } else {
                    error = response.data;
                }

                afterFetchData(allLoaded, error);
            });
		},
		//获取牛人都在买和牛人都在卖数据
		fetchBuySellData(afterFetchData){
			//查询牛人都在买/卖
			var vm = this,
                error = '',
                allLoaded = false,
            	entrust_bs = vm.$route.params.menuindex,
                pageParam = vm.getPageParam();//0-买；1-卖

            RemoteDAO.callJCL30006(entrust_bs, pageParam.end, pageParam.start, function (response) {
                var data;

                if (Number(response.error) == 0) {
                    data = response.data.body.data;

                    data.forEach(function (item,index) {
                        item.stock_code = CommonUtil.getMarketCode(item.exchange_type) + item.stock_code;
                        item.actionState = "1";
                        vm.stockcodes += item.stock_code + "|";
                    });

                    vm.dataList = vm.dataList.concat(data);

                    if(vm.dataList.length == 0){
                      error = '暂无数据'
                    }else if (data.length < vm.pageInfo.pageSize){
                      allLoaded = true
                    }

                    if(!allLoaded){
                        vm.pageInfo.pageNum++;
                    }

                    vm.checkMyStock(pageParam.start,pageParam.start+data.length);
                } else {
                    error = response.data;
                }

                afterFetchData(allLoaded, error);
            });
		},
		fetchData(afterFetchData){
			var vm = this;

	        if (Number(vm.$route.params.menuindex) == 2) {
	            vm.fetchWatchData(afterFetchData);
	        } else {
	            vm.fetchBuySellData(afterFetchData);
	        }
		},
        addRemoveStock(item){
            var vm = this,
                userCode = LocalDAO.getUserCode();

            if(!LocalDAO.getNickname()){//未登录
                var kv = {"usercode": "", "k2": ""};
                TDAPP.onEvent("2010", "", kv);
                TDAPP.send();

                //注册或登录
                RemoteDAO.callNativeLogin(function (response) {
                    if (response.error == 0) {
                      vm.$store.dispatch('setTip',{text: "已为您登录，请重新查看点击"});
                      setTimeout(function () {
                        window.location.reload();
                      },1000)
                    } else {
                        vm.$store.dispatch('setTip',{text:response.data});
                    }
                });
            } else {
                if(item.actionState==2){
                    // 添加到自选股
                    RemoteDAO.addMyStock(item.stock_code, item.stock_name, function (ret) {
                        if (Number(ret.error) == 0) {
                            item.actionState = 3;
                            vm.$store.dispatch('setTip',{text:"添加成功"});
                            vm.myStocks.push(item.stock_code);
                        } else {
                            vm.$store.dispatch('setTip',{text:ret.data});
                        }
                    });

                    var eventid = this.$route.params.menuindex==0 ? "16003" : (this.$route.params.menuindex==1 ? "16005" : "16007");
                    var kv = {"usercode": userCode, "k2": ""};
                    TDAPP.onEvent(eventid, "", kv);
                    TDAPP.send();
                } else if(item.actionState == 3){
                    // 删除自选股
                    RemoteDAO.deleteMyStock(item.stock_code, item.stock_name, function (ret) {
                        if (Number(ret.error) == 0) {
                            item.actionState = 2;
                            vm.$store.dispatch('setTip',{text:"删除成功"});
                            var index = _.indexOf(vm.myStocks, item.stock_code);
                            if (index > -1) {
                                vm.myStocks.splice(index,1);
                            }
                        } else {
                            vm.$store.dispatch('setTip',{text:ret.data});
                        }
                    });
                    var eventid = this.$route.params.menuindex==0 ? "16009" : (this.$route.params.menuindex==1 ? "16010" : "16011");
                    var kv = {"usercode": userCode, "k2": ""};
                    TDAPP.onEvent(eventid, "", kv);
                    TDAPP.send();
                }
            }
        },
        sendStockEvent(index){
            var eventid = index==0?"16002":(index==1?"16004":"16006");
            var userCode = LocalDAO.getUserCode();
            var kv = {"usercode": userCode, "k2": ""};
            TDAPP.onEvent(eventid, "", kv);
            TDAPP.send();
        }
	},
	created(){
		var vm = this;

        if (LocalDAO.getNickname()) {
            vm.isLogin = true;
        } else {
            vm.isLogin = false;
        }

		vm.sendStockEvent(vm.$route.params.menuindex);
	}
}
</script>

<style lang="css">
</style>
